<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <el-form
                    ref="queryForm"
                    :model="queryParams"
                    :inline="true"
                    label-width="68px"
                >
                    <el-form-item label="活动类型" prop="couponType">
                        <el-select
                            v-model="queryParams.couponType"
                            placeholder="用户优惠券类型"
                            clearable
                            size="small"
                        >
                            <el-option
                                v-for="dict in couponTypeOptions"
                                :key="dict.dictValue"
                                :label="dict.dictLabel"
                                :value="dict.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="店铺名称"
                        prop="shopName"
                        v-if="shopId === -1"
                    >
                        <el-input
                            v-model="queryParams.shopName"
                            placeholder="请输入店铺名称"
                            clearable
                            size="small"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="是否到期" prop="status">
                        <el-select
                            v-model="queryParams.status"
                            placeholder="是否到期"
                            clearable
                            size="small"
                        >
                            <el-option label="已到期" value="T" />
                            <el-option label="未到期" value="F" />
                        </el-select>
                    </el-form-item>
                     <el-form-item label="活动状态" prop="isban">
                            <el-select v-model="queryParams.isban">
                                <el-option
                                    v-for="dict in isbanOptions"
                                    :key="dict.dictValue"
                                    :label="dict.dictLabel"
                                    :value="dict.dictValue"
                                    ></el-option
                                >
                            </el-select>
                        </el-form-item>

                    <el-form-item>
                        <el-button
                            type="primary"
                            icon="el-icon-search"
                            size="mini"
                            @click="handleQuery"
                            >搜索</el-button
                        >
                        <el-button
                            icon="el-icon-refresh"
                            size="mini"
                            @click="resetQuery"
                            >重置</el-button
                        >
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            v-permisaction="['platform:shopcoupon:add']"
                            type="primary"
                            icon="el-icon-plus"
                            size="mini"
                            @click="handleAdd"
                            >新增</el-button
                        >
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            v-permisaction="['platform:shopcoupon:edit']"
                            type="success"
                            icon="el-icon-edit"
                            size="mini"
                            :disabled="single"
                            @click="handleUpdate"
                        >
                            修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            v-permisaction="['platform:shopcoupon:remove']"
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            :disabled="multiple"
                            @click="handleDelete"
                        >
                            删除
                        </el-button>
                    </el-col>
                </el-row>

                <el-table
                    v-loading="loading"
                    :data="bwshopcouponList"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                    />
                    <el-table-column
                        label="店铺"
                        align="center"
                        prop="shopName"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <el-image
                                style="
                                    width: 48px;
                                    height: 48px;
                                    border-radius: 48px;
                                "
                                :src="scope.row.shopCover"
                            />
                            {{ scope.row.shopName }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="活动类型"
                        align="center"
                        prop="couponType"
                        :formatter="couponTypeFormat"
                        width="100"
                    >
                        <template slot-scope="scope">
                            {{ couponTypeFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="每日时段"
                        align="center"
                        prop="dayRange"
                        :formatter="couponTypeFormat"
                        width="100"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.startTime }}-{{ scope.row.endTime }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="开始日期"
                        align="center"
                        prop="startDate"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="结束日期"
                        align="center"
                        prop="endDate"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="满减"
                        align="center"
                        prop="useMinMoney"
                        :formatter="couponTypeFormat"
                        width="100"
                    >
                        <template slot-scope="scope">
                            满{{ scope.row.useMinMoney }}返{{
                                scope.row.returnMoney
                            }}
                        </template>
                    </el-table-column>

                    <el-table-column
                        label="固定量"
                        align="center"
                        style="width: 20px"
                        prop="oldNum"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="剩余量"
                        align="center"
                        style="width: 20px"
                        prop="num"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="店铺要求"
                        align="center"
                        width="120"
                        prop="shopClaim"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="禁用"
                        align="center"
                        prop="isban"
                        width="100"
                        class-name="small-padding fixed-width bgf8"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.isbanFlg"
                                @change="changeShopBanned(scope.row)"
                            ></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        class-name="small-padding fixed-width bgf8"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <el-button
                                v-permisaction="['platform:shopcoupon:edit']"
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleUpdate(scope.row)"
                                >修改</el-button
                            >
                            <el-button
                                v-permisaction="['platform:shopcoupon:remove']"
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.row)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />

                <!-- 添加或修改对话框 -->
                <el-dialog
                    :title="title"
                    :visible.sync="open"
                    width="100vw"
                    fullscreen
                    append-to-body
                >
                    <el-form
                        ref="form"
                        :model="form"
                        :rules="rules"
                        label-width="110px"
                    >
                        <el-form-item
                            label="店铺名称"
                            prop="shopId"
                            v-if="shopId === -1"
                        >
                            <el-select
                                v-model="form.shopId"
                                filterable
                                remote
                                reserve-keyword
                                placeholder="请输入关键词"
                                :remote-method="searchShopList"
                                :loading="shopListLoading"
                            >
                                <el-option
                                    v-for="item in shopList"
                                    :key="item.shopId"
                                    :label="item.shopName"
                                    :value="item.shopId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="类型" prop="couponType">
                            <el-select
                                v-model="form.couponType"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="dict in couponTypeOptions"
                                    :key="dict.dictValue"
                                    :label="dict.dictLabel"
                                    :value="Number(dict.dictValue)"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="单日时间" prop="timeRange">
                            <el-time-picker
                                is-range
                                arrow-control
                                v-model="form.timeRange"
                                value-format="HH:mm"
                                format="HH:mm"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                placeholder="选择时间范围"
                            ></el-time-picker>
                        </el-form-item>
                        <el-form-item label="有效时间" prop="timeDateRange">
                            <el-date-picker
                                v-model="form.timeDateRange"
                                type="datetimerange"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                format="yyyy-MM-dd HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                            >
                            </el-date-picker>
                        </el-form-item>
                        <!-- <el-form-item label="结束时间" prop="endTime">
                            <el-input v-model="form.endTime" placeholder="结束时间"
                            />
                        </el-form-item> -->
                        <el-form-item label="最低消费" prop="useMinMoney">
                            <div class="row ali_cen">
                                <el-input
                                    style="width: 250px; margin-right: 10px"
                                    v-model="form.useMinMoney"
                                    placeholder="最低消费"
                                    oninput="value=value.match(/^[1-9]\d*(\.?\d{0,2})/g) && (value.match(/^[1-9]\d*(\.?\d{0,2})/g)[0] || '')"
                                />
                                <span>元</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="返现金额" prop="returnMoney">
                            <div class="row ali_cen">
                                <el-input
                                    style="width: 250px; margin-right: 10px"
                                    v-model="form.returnMoney"
                                    placeholder="最低消费"
                                    oninput="value=value.match(/^[1-9]\d*(\.?\d{0,2})/g) && (value.match(/^[1-9]\d*(\.?\d{0,2})/g)[0] || '')"
                                />
                                <span>元</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="剩余优惠券数量" prop="num"
                            ><el-input-number
                                :min="0"
                                v-model="form.num"
                                placeholder="剩余优惠券数量"
                        /></el-form-item>
                        <el-form-item label="总优惠券数量" prop="oldNum"
                            ><el-input-number
                                :min="0"
                                v-model="form.oldNum"
                                placeholder="总优惠券数量"
                        /></el-form-item>
                         <el-form-item label="店铺要求" prop="shopClaim"
                            ><el-autocomplete
                                                style="width: 100%"
                                                class="inline-input"
                                                type="textarea"
                                                v-model="form.shopClaim"
                                                :fetch-suggestions="querySearch"
                                                placeholder="店铺要求"
                                                value-key="reason"
                                            ></el-autocomplete></el-form-item>
                         <el-form-item label="状态" prop="isban">
                            <el-radio-group v-model="form.isban">
                                <el-radio
                                    v-for="dict in isbanOptions"
                                    :key="dict.dictValue"
                                    :label="dict.dictValue"
                                    >{{ dict.dictLabel }}</el-radio
                                >
                            </el-radio-group>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm"
                            >确 定</el-button
                        >
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </template>
    </BasicLayout>
</template>

<script>
import {
    addBwShopCoupon,
    delBwShopCoupon,
    getBwShopCoupon,
    listBwShopCoupon,
    updateBwShopCoupon,
} from "@/api/bw/platform/shop/shopcoupon";
import { listBwShop, getBwShop } from "@/api/bw/platform/shop/shop";
import { updateBwUser } from "@/api/bw/platform/user/user";
import { listBwReason } from "@/api/bw/platform/reason/index";


export default {
    name: "Config",
    props: {
        shopId: {
            type: [Number, String],
            default: -1,
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            // 类型数据字典
            typeOptions: [],
            bwshopcouponList: [],
            couponTypeOptions: [],
            isbanOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                couponType: undefined,
                shopName: undefined,
                status: '',
                isban: ''
            },
            // 表单参数
            form: {
                timeRange: [],
                timeDateRange: [],
            },
            // 表单校验
            rules: {
                couponType: [
                    {
                        required: true,
                        message: "类型：1饿了么，2:美团不能为空",
                        trigger: "blur",
                    },
                ],
                startTime: [
                    {
                        required: true,
                        message: "开始时间不能为空",
                        trigger: "blur",
                    },
                ],
                endTime: [
                    {
                        required: true,
                        message: "结束时间不能为空",
                        trigger: "blur",
                    },
                ],
                useMinMoney: [
                    {
                        required: true,
                        message: "最低消费不能为空",
                        trigger: "blur",
                    },
                ],
                returnMoney: [
                    {
                        required: true,
                        message: "返现金额不能为空",
                        trigger: "blur",
                    },
                ],
                isban: [
                    {
                        required: true,
                        message: "请选择状态",
                        trigger: "blur",
                    },
                ],
            },

            shopList: [],
            shopListLoading: false,
            reasonList: []
        };
    },
    created() {
        this.getList();
        this.getDicts("shop_coupon_type").then((response) => {
            this.couponTypeOptions = response.data;
        });
         this.getDicts("is_banned").then((response) => {
            this.isbanOptions = response.data;
        });
         listBwReason({
            pageIndex: 1,
            pageSize: 150,
            classId: 2,
        }).then((res) => {
            this.reasonList = res.data.list || [];
        });
    },
    methods: {
        querySearch(queryString, cb) {
            cb(this.reasonList);
        },
        searchShopList(query) {
            if (query) {
                this.shopListLoading = true;
                listBwShop({
                    pageIndex: 1,
                    pageSize: 30,
                    shopName: query,
                }).then((res) => {
                    this.shopList = res.data.list;
                    this.shopListLoading = false;
                });
            } else {
                this.shopList = [];
            }
        },
        /** 查询参数列表 */
        getList() {
            this.loading = true;
            this.loading = true;
            let data = this.addDateRange(
                { ...this.queryParams },
                this.dateRange
            );
            if (this.shopId !== -1) {
                data.shopId = this.shopId;
            }
            listBwShopCoupon(data).then((response) => {
                response.data.list.forEach((item) => {
                    item.isbanFlg = item.isban === "T";
                });
                this.bwshopcouponList = response.data.list;
                this.total = response.data.count;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                shopCouponId: undefined,
                shopId: undefined,
                num: undefined,
                couponType: undefined,
                startTime: undefined,
                endTime: undefined,
                useMinMoney: undefined,
                returnMoney: undefined,
                oldNum: undefined,
                timeDateRange: undefined,
                shopClaim: undefined,
                isban: undefined,

                timeRange: ["00:00", "23:59"],
            };
            if (this.shopId !== -1) {
                this.form.shopId = this.shopId;
            }
            this.resetForm("form");
        },
        couponTypeFormat(row) {
            return this.selectDictLabel(this.couponTypeOptions, row.couponType);
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加用户优惠券";
            this.isEdit = false;
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.shopCouponId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const shopCouponId = row.shopCouponId || this.ids;
            getBwShopCoupon(shopCouponId).then((res) => {
                res.data.timeRange = [res.data.startTime, res.data.endTime];
                res.data.timeDateRange = [res.data.startDate, res.data.endDate];
                getBwShop(res.data.shopId).then((shopRes) => {
                    this.searchShopList(shopRes.data.shopName);
                });
                this.form = res.data;
                this.open = true;
                this.title = "修改用户优惠券";
                this.isEdit = true;
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let temp = { ...this.form };
                    temp.timeRange = temp.timeRange.slice(0);
                    temp.startTime = temp.timeRange[0];
                    temp.endTime = temp.timeRange[1];
                    temp.timeDateRange = temp.timeDateRange.slice(0);
                    temp.startDate = temp.timeDateRange[0];
                    temp.endDate = temp.timeDateRange[1];
                    temp.returnMoney = Number(temp.returnMoney);
                    temp.useMinMoney = Number(temp.useMinMoney);
                    temp.couponType = Number(temp.couponType);
                    delete temp.timeRange;
                    delete temp.timeDateRange;
                    if (this.form.shopCouponId !== undefined) {
                        updateBwShopCoupon(temp).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    } else {
                        addBwShopCoupon(temp).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const Ids = row.shopCouponId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delBwShopCoupon(Ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () {});
        },
        changeShopBanned(row) {
            row.isban = row.isbanFlg ? "T" : "F";

            updateBwShopCoupon(row).then((response) => {
                if (response.code === 200) {
                    this.msgSuccess("修改成功");
                } else {
                    this.msgError(response.msg);
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.diaga {
    z-index: 3000 !important;
}
</style>
